package com.ruoyi.system.utils;

import java.io.FileOutputStream;
import java.io.InputStream;

import com.aspose.cells.*;

public class ExcelToPdf {

    public static boolean getLicense() {
        boolean result = false;
        try {

            InputStream inputStream = ClassLoader.getSystemResourceAsStream("excel/license.xml");
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("excel/license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void excel2pdf(String sourceFilePath, String desFilePathd) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {

            Workbook wb = new Workbook(sourceFilePath);// 原始excel路径

            FileOutputStream fileOS = new FileOutputStream(desFilePathd);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            int[] autoDrawSheets = {3};
            //当excel中对应的sheet页宽度太大时，在PDF中会拆断并分页。此处等比缩放。
            autoDraw(wb, autoDrawSheets);
            int[] showSheets = {0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb, showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            //System.out.println("转换PDF完毕！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void autoDraw(Workbook wb, int[] page) {
        if (null != page && page.length > 0) {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }


    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb, int[] page) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == page || page.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    public static void main(String[] args) {
        String path1 = "C:/Users/lovec/Desktop/感谢状 (1).xls"; //现存的excel文件全路径 + 文件名 + 后缀
        String path2 = "C:/Users/lovec/Desktop/感谢状 (1).pdf"; //要生成的pdf文件全路径 + 文件名 + 后缀
        ExcelToPdf.excel2pdf(path1, path2);

    }
}
